package com.everflourish.yeah100.act.menu;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseFragment;
import com.everflourish.yeah100.adapter.ExaminationAdapter;
import com.everflourish.yeah100.entity.Examination;
import com.everflourish.yeah100.entity.ExaminationModel;
import com.everflourish.yeah100.entity.VersionInfo;
import com.everflourish.yeah100.http.ExaminationRequest;
import com.everflourish.yeah100.http.SettingRequest;
import com.everflourish.yeah100.service.VersionUpdateService;
import com.everflourish.yeah100.ui.AutoLoadRecylerView;
import com.everflourish.yeah100.utils.IntentUtil;
import com.everflourish.yeah100.utils.LogUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.VersionUtil;
import com.everflourish.yeah100.utils.Yeah100;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.ResultCode;
import com.everflourish.yeah100.utils.constant.RoleEnum;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者：Created by liqisi on 2016/6/1.
 * 时间：2016/6/1
 */
public class FragmentExam extends BaseFragment implements AutoLoadRecylerView.LoadMoreListener {

    public HomeActivity mActivity;
    public ExaminationRequest mRequest;
    public SettingRequest mSettingRequest;
    private AutoLoadRecylerView mExaminationList;
    public SwipeRefreshLayout mSwipeRefreshLayout;
    public SwipeRefreshLayout.OnRefreshListener mRefreshListener;
    private List<ExaminationModel> mList;
    private ExaminationAdapter mAdapter;
    private boolean isLoadMore = false;  // 是否加载更多
    private boolean isRefreshOrLoadMore = false;  // 是否在刷新或者加载
    public String mExaminationName = "";
    public TextView mEmptyTv;

    /**
     * 每次加载10条
     */
    private int mSelectCount = 10;
    /**
     * 加载的位置
     */
    private int mStartIndex = 0;
    /**
     * 获取考试信息是否包含软删除
     */
    private Boolean mIncludeDeletedRecord = false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_exam, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
        initWidget();
        configView();
    }

    private void initData() {
        mContext = mActivity = (HomeActivity) getActivity();
        mRequest = ExaminationRequest.getInstance();
        mSettingRequest = SettingRequest.getInstance();
        mList = new ArrayList<ExaminationModel>();
        mAdapter = new ExaminationAdapter(mContext, mList, this);
    }

    private void initWidget() {
        mExaminationList = (AutoLoadRecylerView) getView().findViewById(R.id.exam_list);
        mSwipeRefreshLayout = (SwipeRefreshLayout) getView().findViewById(R.id.swipe);
        mEmptyTv = (TextView) getView().findViewById(R.id.exam_empty_tv);
    }

    @SuppressWarnings("ResourceType")
    private void configView() {
        mExaminationList.setLayoutManager(new LinearLayoutManager(getActivity()));
        mExaminationList.setAdapter(mAdapter);
        mRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mExaminationName = "";
                searchExaminationInfo();
            }
        };
        mSwipeRefreshLayout.setColorScheme(R.color.colorPrimary);
        mSwipeRefreshLayout.setOnRefreshListener(mRefreshListener);
        mSwipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshLayout.setRefreshing(true);
            }
        });
        mRefreshListener.onRefresh();
//        mExaminationList.setVisibility(View.GONE);
        // 延时3s后再去请求版本的更新
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                versionDetectRequest();
            }
        }, 3000);
    }

    @Override
    public void onLoadMore() {
        isLoadMore = true;
        if (!isRefreshOrLoadMore) {
            searchExaminationInfo();
        }
    }

    /**
     * 检查是否是最新版本请求
     */
    private void versionDetectRequest() {
        String versionName = VersionUtil.getVersionName(mContext);
        String appName = VersionUtil.APP_NAME;
        JsonObjectRequest request = mSettingRequest.softwareVersionRequest(appName,
                versionName, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        versionListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                });
        mQueue.add(request);
    }

    public void searchExaminationInfo() {
        if (isLoadMore) {  // 加载更多
            mStartIndex = mStartIndex + mSelectCount;
        } else { // 下拉刷新
            mStartIndex = 0;
        }
        getExamList(Yeah100.mRoleEnum, mStartIndex, mSelectCount, mExaminationName, null, null,
                null, mIncludeDeletedRecord, null);
    }

    /**
     * 获取考试列表信息
     *
     * @param roleEnum             角色
     * @param startIndex           开始位置
     * @param selectedCount        获取数量(默认10条)
     * @param examinationName      考试名称（支持模糊查询）
     * @param subject              科目名称
     * @param DateFrom             查询的开始时间
     * @param dateTo               查询的结束时间
     * @param includeDeletedRecord 是否包含已删除的考试信息
     */
    private void getExamList(RoleEnum roleEnum, Integer startIndex,
                             Integer selectedCount, String examinationName, String subject,
                             String DateFrom, String dateTo, Boolean includeDeletedRecord,
                             String friendId) {
        isRefreshOrLoadMore = true;
        mEmptyTv.setVisibility(View.GONE);
        JsonObjectRequest request = mRequest
                .examinationListRequest(roleEnum, startIndex, selectedCount,
                        examinationName, subject, DateFrom, dateTo,
                        includeDeletedRecord, friendId,
                        new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {
                                examListener(response);
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                isRefreshOrLoadMore = false;
                                mRequest.disposeError(mContext, mLoadDialog, error, "获取考试列表失败");
                                isLoadMore = false;
                                mSwipeRefreshLayout.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        mSwipeRefreshLayout.setRefreshing(false);
                                    }
                                });
                                mExaminationList.setLoading(false);
                            }
                        });
        mQueue.add(request);
//        mQueue.start();
    }

    /**
     * 获取考试列表成功响应
     *
     * @param response
     */
    private void examListener(JSONObject response) {
        int totalCount = 0;
        try {
            String resultCode = response.getString(Constant.RESULT_CODE);
            totalCount = response.getInt(Constant.TOTALCOUNT);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                JSONArray jsonArray = response
                        .getJSONArray(Constant.EXAMINATIONS);
                Gson gson = new Gson();
                Type type = new TypeToken<List<Examination>>() {
                }.getType();
                List<Examination> examList = gson.fromJson(
                        jsonArray.toString(), type);
                if (examList == null || examList.size() == 0) {
//                    MyToast.showShort(mContext, "没有找到相关的考试信息");
                    mEmptyTv.setVisibility(View.VISIBLE);
                    mList.clear();
                }
                if (!isLoadMore) {
                    mList.clear();
                }
                setExaminationModelList(examList);
                mAdapter.notifyDataSetChanged();
            } else {
                if (Yeah100.mRoleEnum == RoleEnum.STUDENT) {
                    if (resultCode.equals(ResultCode.result_system_exception_999999E)) {
                        MyToast.showShort(mContext, R.string.examination_081499_999999E);
                    } else {
                        MyToast.showShort(mContext, "获取考试信息失败");
                    }
                } else if (Yeah100.mRoleEnum == RoleEnum.TEACHER) {
                    if (resultCode.equals(ResultCode.result_000012E.resultCode)) {
                        MyToast.showShort(mContext, R.string.examination_08151_000012E);
                    } else if (resultCode.equals(ResultCode.result_system_exception_999999E)) {
                        MyToast.showShort(mContext, R.string.examination_081599_999999E);
                    } else {
                        MyToast.showShort(mContext, "获取考试信息失败");
                    }
                }
            }
        } catch (Exception e) {
            LogUtil.e("Json异常", e);
            MyToast.showShort(mContext, "获取考试信息失败");
        } finally {
//            mExaminationList.setVisibility(View.VISIBLE);
            mAdapter.notifyItemRangeInserted(0, mList.size() - 1);
            isLoadMore = false;
            mExaminationList.setLoading(false);
            isRefreshOrLoadMore = false;
            mSwipeRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            });
            if (mList.size() >= totalCount) {
                mExaminationList.setLoadMoreListener(null);
            } else {
                mExaminationList.setLoadMoreListener(this);
            }
        }
    }

    /**
     * 检测版本更新监听
     *
     * @param response
     */
    private void versionListener(JSONObject response) {
        try {
            String resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                Integer latestVersion = response.getInt("latestVersion");
                if (latestVersion == null || latestVersion == 1) {
                    return;
                }
                // 有最新版本
                JSONObject jsonObject = response
                        .getJSONObject("latestVersionInfo");
                Gson gson = new Gson();
                Yeah100.versionInfo = gson.fromJson(jsonObject.toString(),
                        VersionInfo.class);
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle("发现新版本" + Yeah100.versionInfo.getLatestVersion());
                builder.setMessage(Yeah100.versionInfo.getChanges());
                builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
                                && ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions(mActivity,
                                    new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 210);
                        }
                        Intent service = new Intent(mContext, VersionUpdateService.class);
                        mActivity.startService(service);
                    }
                });
                builder.setNegativeButton("稍后再说", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将examination封装成examinationModel
     *
     * @param list
     */
    private void setExaminationModelList(List<Examination> list) {
        for (Examination examination : list) {
            ExaminationModel examinationModel = new ExaminationModel();
            examinationModel.setExamination(examination);
            examinationModel.setIsOperation(false);
            examinationModel.setIsChecked(false);
            mList.add(examinationModel);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == mActivity.RESULT_OK) {
            if (requestCode == 0x100) {
                if (data.getBooleanExtra(IntentUtil.IS_UPDATE, false)) {
                    mRefreshListener.onRefresh();
                }
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}